<?php

namespace App\Repos;

use App\Models\Coupon;
use App\Models\UserCoupon;
use App\Models\User;
use DB;

class CouponRepo 
{
    public static function getList($where=[])
    {
        //dd($where);
        $data = Coupon::where($where)->get();

        return $data;
    }

    public static function pages($where=[])
    {
        $list = Coupon::where($where)->paginate(10);
        return $list;
    }

    public static function create($data)
    {
        $data = Coupon::create($data);
        return $data;
    }

    public static function save($data)
    {
    	$rs['status'] = true;
    	try {
    		$flag = Coupon::create($data);	
            $rs['data'] = $flag;
    	} catch (\Exception $e) {
    		$rs['status'] = false;
    		$rs['msg'] = $e->getMessage();
    		return $rs;
    	}    	
    	return $rs;
    }

    public static function update($where,$data)
    {
        $rs['status'] = true;
        //dd($data);
        try {
            $flag = Coupon::where($where)->update($data);  
            $rs['data'] = $flag;
        } catch (\Exception $e) {
            $rs['status'] = false;
            $rs['msg'] = $e->getMessage();
            return $rs;
        }       
        return $rs;
    }

    public static function delete($id)
    {
        $rs['status'] = true;
        try {
            $flag = Coupon::where(['id'=>$id])->delete();  
        } catch (\Exception $e) {
            $rs['status'] = false;
            $rs['msg'] = $e->getMessage();
            return $rs;
        }       
        return $rs;
    }

    public static function find($where)
    {
        return Coupon::where($where)->first();
    }

    public static function useCoupon($data) 
    {
        $rs['status'] = false;
        $coupon = Coupon::where(['code'=>$data['code']])->first();
        if(!$coupon) {
            $rs['msg'] = '优惠券不存在';
            return $rs;
        }

        if($coupon->status==0){
            $rs['msg'] = '优惠券已被使用';
            return $rs;
        }

        DB::beginTransaction();
        try {
            // 优惠券作废
            $coupon->status=0;
            $coupon->save();

            // 用户加积分
            $user = User::find($data['user_id']);
            $user->coupon_point += $coupon->point;
            $user->save();
           
            // 保存使用记录
            $uc['user_id']   = $data['user_id'];
            $uc['coupon_id'] = $coupon->id;
            $uc['coupon_point'] = $coupon->point;
            $uc['type'] = 1;
            $flag = UserCoupon::create($uc);
            DB::commit();
            $rs['status'] = true;
            return $rs;
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();           
            DB::rollBack();
            return $rs;
        }
        

        return $rs;


    }

    public static function log($where=[])
    {
       
        $data = UserCoupon::where($where)->orderBy('created_at','desc')->paginate(10);

        return $data;
    }
}
